/*
 * Copyright 2021 The happyProxy Project
 *
 * The happyProxy Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.sinosoft.lingkang.happyproxy;

import io.netty.buffer.ByteBuf;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpRequestEncoder;
import java.io.IOException;
import java.util.Base64;

/**
 * @Author 绫小路
 * @Date 2021/2/22
 */
public class HappyProxyUtils {

  public static ByteBuf httpRequestToByteBuf(HttpRequest request) {
    EmbeddedChannel em = new EmbeddedChannel(new HttpRequestEncoder());
    em.writeOutbound(request);
    ByteBuf byteBuf = em.readOutbound();
    em.close();
    return byteBuf;
  }

  public static boolean isEmpty(String o) {
    return o == null || o.length() == 0;
  }


  /**
   * proxy authorization 编码 具体可参考http请求头 Proxy-Authorization 详细说明
   *
   * @param username
   * @param password
   * @return
   */
  public static String accountToProxyAuthEncoder(String username, String password) {
    return Base64.getEncoder().encodeToString(("Basic " + username + ":" + password).getBytes());
  }

  /**
   * proxy authorization 解码 具体可参考http请求头 Proxy-Authorization 详细说明
   *
   * @param proxyAuth
   * @return
   */
  public static String proxyAuthDecoder(String proxyAuth) throws IOException {
    return new String(Base64.getDecoder().decode(proxyAuth));
  }
}
